package robuin.ioio.config;

//import robuin.ioio.config.IOIOSeek.SlowAdapter;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import robuin.ioio.config.R;
import ioio.lib.api.Uart;
import ioio.lib.api.Uart.Parity;
import ioio.lib.api.Uart.StopBits;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.android.IOIOActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import ioio.lib.util.BaseIOIOLooper;
import ioio.lib.util.IOIOLooper;

	public class uartConnect extends IOIOActivity{
		private IOIOThread ioioThread;
	    private TextView mStatus;
	    private TextView outputTextView;
	    private InputStream iStream;
	    private OutputStream oStream;
	    private int rxPin, txPin;
	    private int baudRate;
	    
	    class IOIOThread extends BaseIOIOLooper {
	    	private Uart uart;

	    	@Override
			public void setup() throws ConnectionLostException, InterruptedException {
				try {
					uart = ioio_.openUart(rxPin, txPin, baudRate, Parity.NONE, StopBits.ONE);
					iStream = uart.getInputStream();
					oStream = uart.getOutputStream();
					enableUi(true);

					Thread.sleep(100);
				} catch (ConnectionLostException e) {
					enableUi(false);
					throw e;
				} catch (InterruptedException e) {
					ioio_.disconnect();
					throw e;
				} 
			}
			
	    	@Override
			public void loop() throws ConnectionLostException, InterruptedException {
				try {
					readFromInputStream();
					
					Thread.sleep(100);
				} catch (InterruptedException e) {
					ioio_.disconnect();
					throw e;
				} /*catch (ConnectionLostException e) {
					enableUi(false);
					throw e;
				}*/
			}
	    	
	    	@Override
	    	public void disconnected(){
	    		if(uart != null)
	    			uart.close();
	    	}
		}
	    
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);

	        Intent intent = getIntent();
	        String message = intent.getStringExtra(IOIOConfig.EXTRA_MESSAGE);
	        rxPin = Integer.parseInt(intent.getStringExtra("RX_PIN"));
	        txPin = Integer.parseInt(intent.getStringExtra("TX_PIN"));
	        baudRate = Integer.parseInt(intent.getStringExtra("BAUD_RATE"));
	        
	        setContentView(R.layout.uartconnect);

	        outputTextView = (TextView)findViewById(R.id.textViewOutput);
	        mStatus = (TextView) findViewById(R.id.status1);
	        mStatus.setText(message);
	        enableUi(false);
	    }
	    
	    void readFromInputStream() {
	    	if(iStream == null)
	    		return;
	    	
	    	try {
	    		int numDataBytes = iStream.available();
				if(numDataBytes > 0) {
					byte[] dataBytes = new byte[numDataBytes];
					final StringBuilder sBuilder = new StringBuilder(outputTextView.getText());
					//StringBuilder sBuilder = new StringBuilder();
					iStream.read(dataBytes);
					for(int i = 0; i < numDataBytes; i++) {
						sBuilder.append((char)dataBytes[i]);
					}
					
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							outputTextView.setText(sBuilder.toString());
							//outputTextView.append(sBuilder.toString());
						}
					});
					
				}
			} catch (IOException e) {
				Toast errorMsg = Toast.makeText(null, " An exception occured while recieving data.", Toast.LENGTH_SHORT);
		    	errorMsg.setGravity(Gravity.AXIS_SPECIFIED, 0, 0);
		    	errorMsg.show();
			}
	    }
	    

    	void writeToOutputStream(CharSequence data) {
    		if(oStream == null || data == null)
    			return;
    		
    		byte[] dataBytes = new byte[data.length()];
            for (int i = 0; i < dataBytes.length; i++) {
            	dataBytes[i] = (byte)data.charAt(i);
            }
            
    		try {
				oStream.write(dataBytes);
			} catch (IOException e) {
				Toast errorMsg = Toast.makeText(null, " An exception occured while transmitting data.", Toast.LENGTH_SHORT);
		    	errorMsg.setGravity(Gravity.AXIS_SPECIFIED, 0, 0);
		    	errorMsg.show();
			}
    	}
    	
    	public void buttonOnClick(View v) {
    		EditText editText = (EditText)findViewById(R.id.editTextInput);
    		String text = editText.getText().toString();
    		writeToOutputStream(text);
		}
	    
	    protected IOIOLooper createIOIOLooper() {
			ioioThread = new IOIOThread();
			return ioioThread;
		}
	    
		private void enableUi(final boolean enable) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					// disable button and edittext
				}
			});
		}
	}